package com.example.springboot.service;

import com.example.springboot.entity.Student;
import com.example.springboot.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;

    public List<Student> getAllStudent() {
        return studentMapper.findAllStudent();
    }

    public List<Student> getAllEmail() {
        return studentMapper.findAllEmail();
    }

    public Student findStudent(Student loginRequest) {
        return studentMapper.findStudent(loginRequest.getEmail(), loginRequest.getPhoneNumber());
    }

    public Student getUserInfo(String email) {
        return studentMapper.findUserInfoByEmail(email);
    }

    public void register(Student student) throws Exception {
        int studentID = generateRandomStudentID();
        student.setStudentID(studentID);

        if (student.getEmail() != null && !student.getEmail().isEmpty()) {
            if (!student.getEmail().matches("^[\\w-\\.]+@qq\\.com$")) {
                throw new Exception("邮箱格式不正确");
            }
        } else if (student.getPhoneNumber() != null && !student.getPhoneNumber().isEmpty()) {
            if (!student.getPhoneNumber().matches("^\\d{11}$")) {
                throw new Exception("手机号格式不正确");
            }
        } else {
            throw new Exception("必须提供邮箱或手机号");
        }

        if (!isValidPassword(student.getPassword())) {
            throw new Exception("密码必须包含大小写字母");
        }

        studentMapper.register(student);
    }

    private int generateRandomStudentID() {
        Random random = new Random();
        return random.nextInt(900000) + 100000; // 生成范围 [100000, 999999]
    }

    private boolean isValidPassword(String password) {
        return password.matches("^(?=.*[a-z])(?=.*[A-Z]).+$"); // 至少一个小写字母和一个大写字母
    }

    public boolean emailExists(String email) {
        return studentMapper.findStudentByEmail(email) != null;
    }

    public boolean phoneExists(String phoneNumber) {
        return studentMapper.findStudentByPhone(phoneNumber) != null;
    }

    public boolean checkPassword(String email, String password) {
        Student student = studentMapper.findStudentByEmail(email);
        return student != null && student.getPassword().equals(password);
    }

    public void updateEmail(String oldEmail, String newEmail) {
        studentMapper.updateEmail(oldEmail, newEmail);
    }

    public void updatePhone(String oldPhone, String newPhone) {
        studentMapper.updatePhone(oldPhone, newPhone);
    }

    public void updatePassword(String email, String newPassword) {
        studentMapper.updatePassword(email, newPassword);
    }
}
